<?php
// class GenericDBO
//   

class genericDBO
{
  public $obj; // object's fields
  public $tbl; // object's table name
  public $db;  // connection to the database

  public $classId;
  public $className;

  function __construct($db)
  {
    $this->className = get_class($this);
    $this->tbl = TABLE_PREFIX.$this->className;

    $this->db = $db;
    if (!isset($this->db->tables[$this->tbl])){ // $db should select tables from db
      $this->createTable();
      $this->initData();
    }
  }
  
  function initData()
  {
    return true;
  }
  
  function createTable()
  {
    return //addTable should set db->tables[$this->tbl]
      $this->db->addTable("");
  }
  
  function loadById($id)
  {
    return $this->loadBySql("SELECT * FROM $this->tbl WHERE `id`=".quote_smart($id));
  }
  
  function loadRandom()
  {
    return $this->loadBySql("SELECT * FROM $this->tbl ORDER BY RAND() LIMIT 1,1");
  }

  function loadBySql($sql)
  {
    $res = $this->db->query($sql);
    if  (!($obj = mysql_fetch_object($res)))
      return false;
    else
    {
      $this->obj = $obj;
      return $this->obj;
    };
  }

  function saveToDb()
  {
    $sql = "";

    foreach ($this->obj as $key=>$value)
      $sql.= ($sql?", `":"`").$key."`=".quote_smart($value);

    $sql = "update $this->tbl set ".$sql." where `id`=".quote_smart($this->id());
    return $this->db->query($sql);
  }
      
  function insertToDb()
  {
    $sql = "";

    foreach ($this->obj as $key=>$value)
      $sql.= ($sql?", `":"`").$key."`=".quote_smart($value);

    $sql = "insert into $this->tbl set ".$sql;
    if ($this->db->query($sql))
      return $this->obj->id = mysql_insert_id();
    else
      return false;
  }

  function result($sql)
  {
    $res = $this->db->query($sql);
    if( !($row = mysql_fetch_row($res)) ) return false;
    else return $row[0];
  }

  function count()
  {
    return $this->result("SELECT count(*) FROM $this->tbl");
  }
  
  function delete()
  {
    $sql = "delete from $this->tbl where `id`=".quote_smart($this->id());
    $this->db->query($sql);
    $this->reset();
  }
  
  function asArray()
  {
    $res = $this->db->query("SELECT * FROM $this->tbl");
    $result = array();
    while($r = mysql_fetch_assoc($res))
      $result[$r[$this->classId]] = $r;
    return $result;
  }
  
  function id()
  {
    if (isset($this->obj->id))
      return $this->obj->id;
    else
      return false;
  }
  
  function update($fields)
  {
    foreach ($fields as $field => $value)
      $this->obj->{$field} = $value;
  }
  
  function reset()
  {
    $this->obj = new stdClass();
  }

}
?>